import React, { useState, useMemo } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  InputAdornment,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Chip,
  IconButton,
  Menu,
  MenuList,
  MenuItem as MenuOption,
  ListItemIcon,
  ListItemText,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Divider,
} from '@mui/material';
import {
  Search as SearchIcon,
  Add as AddIcon,
  FilterList as FilterIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  MoreVert as MoreVertIcon,
  Visibility as ViewIcon,
  AccountTree as TreeIcon,
  ExpandMore as ExpandMoreIcon,
  Business as BusinessIcon,
  Group as GroupIcon,
  Settings as SettingsIcon,
  Warning as WarningIcon,
} from '@mui/icons-material';
import { TreeView, TreeItem } from '@mui/x-tree-view';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

import { 
  Organization, 
  OrganizationFilter, 
  Status,
  PaginatedResponse,
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { organizationService } from '@/services/organizationService';
import { PageHeader } from '@/components/common/PageHeader';

const OrganizationListPage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { hasPermission, currentTenant } = useAuth();
  const { showToast } = useAppNotifications();

  // 状态管理
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<Status | ''>('');
  const [viewMode, setViewMode] = useState<'tree' | 'list'>('tree');
  const [selectedOrganization, setSelectedOrganization] = useState<Organization | null>(null);
  const [actionMenuAnchor, setActionMenuAnchor] = useState<null | HTMLElement>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [organizationToDelete, setOrganizationToDelete] = useState<Organization | null>(null);
  const [expandedNodes, setExpandedNodes] = useState<string[]>(['1']);

  // 构建查询参数
  const queryParams = useMemo(() => {
    const params: OrganizationFilter = {};

    if (currentTenant) {
      params.tenantId = currentTenant.id;
    }
    if (searchQuery.trim()) {
      params.search = searchQuery.trim();
    }
    if (statusFilter) {
      params.status = statusFilter;
    }

    return params;
  }, [searchQuery, statusFilter, currentTenant]);

  // 获取组织列表
  const {
    data: organizationData,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['organizations', queryParams],
    queryFn: () => organizationService.getOrganizations(queryParams),
    enabled: !!currentTenant,
  });

  // 删除组织
  const deleteMutation = useMutation({
    mutationFn: organizationService.deleteOrganization,
    onSuccess: () => {
      showToast({
        type: 'success',
        title: '删除成功',
        message: '组织已成功删除',
      });
      queryClient.invalidateQueries(['organizations']);
      setDeleteDialogOpen(false);
      setOrganizationToDelete(null);
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '删除失败',
        message: error.message || '删除组织时发生错误',
      });
    },
  });

  // 构建组织树形结构
  const organizationTree = useMemo(() => {
    if (!organizationData?.data) return [];

    const organizations = organizationData.data;
    const tree: Organization[] = [];
    const map = new Map<string, Organization & { children: Organization[] }>();

    // 创建映射
    organizations.forEach(org => {
      map.set(org.id, { ...org, children: [] });
    });

    // 构建树形结构
    organizations.forEach(org => {
      const node = map.get(org.id)!;
      if (org.parentId && map.has(org.parentId)) {
        map.get(org.parentId)!.children.push(node);
      } else {
        tree.push(node);
      }
    });

    return tree;
  }, [organizationData]);

  // 过滤组织（用于搜索）
  const filteredOrganizations = useMemo(() => {
    if (!organizationData?.data) return [];

    let filtered = organizationData.data;

    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(org => 
        org.name.toLowerCase().includes(query) ||
        org.code.toLowerCase().includes(query) ||
        org.description?.toLowerCase().includes(query)
      );
    }

    if (statusFilter) {
      filtered = filtered.filter(org => org.status === statusFilter);
    }

    return filtered;
  }, [organizationData, searchQuery, statusFilter]);

  // 渲染组织状态
  const renderStatus = (status: Status) => {
    const statusConfig = {
      active: { label: '启用', color: 'success' as const },
      inactive: { label: '禁用', color: 'error' as const },
      pending: { label: '待审核', color: 'warning' as const },
      suspended: { label: '暂停', color: 'error' as const },
    };

    const config = statusConfig[status] || statusConfig.inactive;
    return <Chip label={config.label} color={config.color} size="small" />;
  };

  // 渲染树形节点
  const renderTreeNode = (org: Organization & { children?: Organization[] }) => (
    <TreeItem
      key={org.id}
      nodeId={org.id}
      label={
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, py: 0.5 }}>
          <BusinessIcon color="primary" fontSize="small" />
          <Box sx={{ flex: 1 }}>
            <Typography variant="subtitle2" noWrap>
              {org.name}
            </Typography>
            <Typography variant="caption" color="text.secondary" noWrap>
              {org.code} • 等级 {org.level}
            </Typography>
          </Box>
          {renderStatus(org.status)}
          <IconButton
            size="small"
            onClick={(e) => handleMoreActions(e, org)}
            sx={{ ml: 1 }}
          >
            <MoreVertIcon fontSize="small" />
          </IconButton>
        </Box>
      }
    >
      {org.children?.map(child => renderTreeNode(child))}
    </TreeItem>
  );

  // 处理更多操作菜单
  const handleMoreActions = (event: React.MouseEvent<HTMLButtonElement>, org: Organization) => {
    event.stopPropagation();
    setActionMenuAnchor(event.currentTarget);
    setSelectedOrganization(org);
  };

  // 关闭操作菜单
  const handleCloseActionMenu = () => {
    setActionMenuAnchor(null);
    setSelectedOrganization(null);
  };

  // 处理删除组织
  const handleDeleteOrganization = (org: Organization) => {
    // 检查是否有子组织
    const hasChildren = organizationData?.data?.some(o => o.parentId === org.id);
    
    if (hasChildren) {
      showToast({
        type: 'warning',
        title: '无法删除',
        message: '该组织下还有子组织，请先删除子组织',
      });
      return;
    }

    setOrganizationToDelete(org);
    setDeleteDialogOpen(true);
    handleCloseActionMenu();
  };

  // 确认删除
  const confirmDelete = () => {
    if (organizationToDelete) {
      deleteMutation.mutate(organizationToDelete.id);
    }
  };

  // 清除筛选
  const handleClearFilters = () => {
    setSearchQuery('');
    setStatusFilter('');
  };

  if (!currentTenant) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="warning">
          请先选择租户
        </Alert>
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">
          加载组织列表失败：{(error as any).message}
        </Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="组织管理"
        description="管理组织架构和层级关系"
        actions={
          hasPermission('organization.create') ? (
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => navigate('/organizations/create')}
            >
              创建组织
            </Button>
          ) : undefined
        }
      />

      <Card>
        <CardContent>
          {/* 筛选工具栏 */}
          <Box sx={{ mb: 3, display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'center' }}>
            <TextField
              placeholder="搜索组织名称或编码..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
              sx={{ minWidth: 300 }}
            />

            <FormControl sx={{ minWidth: 120 }}>
              <InputLabel>状态</InputLabel>
              <Select
                value={statusFilter}
                label="状态"
                onChange={(e) => setStatusFilter(e.target.value as Status)}
              >
                <MenuItem value="">全部</MenuItem>
                <MenuItem value="active">启用</MenuItem>
                <MenuItem value="inactive">禁用</MenuItem>
                <MenuItem value="pending">待审核</MenuItem>
                <MenuItem value="suspended">暂停</MenuItem>
              </Select>
            </FormControl>

            <FormControl sx={{ minWidth: 120 }}>
              <InputLabel>视图模式</InputLabel>
              <Select
                value={viewMode}
                label="视图模式"
                onChange={(e) => setViewMode(e.target.value as 'tree' | 'list')}
              >
                <MenuItem value="tree">树形视图</MenuItem>
                <MenuItem value="list">列表视图</MenuItem>
              </Select>
            </FormControl>

            <Button
              variant="outlined"
              startIcon={<FilterIcon />}
              onClick={handleClearFilters}
            >
              清除筛选
            </Button>
          </Box>

          {/* 内容区域 */}
          {isLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
              <Typography>加载中...</Typography>
            </Box>
          ) : viewMode === 'tree' ? (
            /* 树形视图 */
            <Box sx={{ minHeight: 400 }}>
              {organizationTree.length > 0 ? (
                <TreeView
                  defaultCollapseIcon={<ExpandMoreIcon />}
                  defaultExpandIcon={<TreeIcon />}
                  expanded={expandedNodes}
                  onNodeToggle={(event, nodeIds) => setExpandedNodes(nodeIds)}
                >
                  {organizationTree.map(org => renderTreeNode(org))}
                </TreeView>
              ) : (
                <Box sx={{ textAlign: 'center', py: 4 }}>
                  <BusinessIcon sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
                  <Typography variant="h6" color="text.secondary" gutterBottom>
                    暂无组织数据
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    点击"创建组织"按钮开始创建第一个组织
                  </Typography>
                </Box>
              )}
            </Box>
          ) : (
            /* 列表视图 */
            <Box>
              {filteredOrganizations.length > 0 ? (
                <Grid container spacing={2}>
                  {filteredOrganizations.map((org) => (
                    <Grid item xs={12} md={6} lg={4} key={org.id}>
                      <Card variant="outlined" sx={{ height: '100%' }}>
                        <CardContent>
                          <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 2 }}>
                            <BusinessIcon color="primary" />
                            <Box sx={{ flex: 1, minWidth: 0 }}>
                              <Typography variant="h6" noWrap>
                                {org.name}
                              </Typography>
                              <Typography variant="body2" color="text.secondary" noWrap>
                                {org.code}
                              </Typography>
                            </Box>
                            <IconButton
                              size="small"
                              onClick={(e) => handleMoreActions(e, org)}
                            >
                              <MoreVertIcon />
                            </IconButton>
                          </Box>

                          {org.description && (
                            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                              {org.description}
                            </Typography>
                          )}

                          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            {renderStatus(org.status)}
                            <Typography variant="caption" color="text.secondary">
                              等级 {org.level}
                            </Typography>
                          </Box>

                          <Divider sx={{ my: 1 }} />

                          <Box sx={{ display: 'flex', gap: 1, fontSize: '0.875rem', color: 'text.secondary' }}>
                            <GroupIcon fontSize="small" />
                            <Typography variant="caption">
                              最大用户: {org.settings?.maxUsers || 0}
                            </Typography>
                          </Box>
                        </CardContent>
                      </Card>
                    </Grid>
                  ))}
                </Grid>
              ) : (
                <Box sx={{ textAlign: 'center', py: 4 }}>
                  <BusinessIcon sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
                  <Typography variant="h6" color="text.secondary" gutterBottom>
                    未找到匹配的组织
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    尝试调整搜索条件或创建新组织
                  </Typography>
                </Box>
              )}
            </Box>
          )}
        </CardContent>
      </Card>

      {/* 更多操作菜单 */}
      <Menu
        anchorEl={actionMenuAnchor}
        open={Boolean(actionMenuAnchor)}
        onClose={handleCloseActionMenu}
        PaperProps={{
          sx: { minWidth: 180 },
        }}
      >
        <MenuList>
          <MenuOption onClick={() => {
            if (selectedOrganization) {
              navigate(`/organizations/${selectedOrganization.id}`);
            }
            handleCloseActionMenu();
          }}>
            <ListItemIcon>
              <ViewIcon />
            </ListItemIcon>
            <ListItemText primary="查看详情" />
          </MenuOption>
          
          {hasPermission('organization.edit') && (
            <MenuOption onClick={() => {
              if (selectedOrganization) {
                navigate(`/organizations/${selectedOrganization.id}/edit`);
              }
              handleCloseActionMenu();
            }}>
              <ListItemIcon>
                <EditIcon />
              </ListItemIcon>
              <ListItemText primary="编辑组织" />
            </MenuOption>
          )}
          
          {hasPermission('organization.create') && (
            <MenuOption onClick={() => {
              if (selectedOrganization) {
                navigate(`/organizations/create?parentId=${selectedOrganization.id}`);
              }
              handleCloseActionMenu();
            }}>
              <ListItemIcon>
                <AddIcon />
              </ListItemIcon>
              <ListItemText primary="创建子组织" />
            </MenuOption>
          )}
          
          {hasPermission('organization.delete') && (
            <MenuOption 
              onClick={() => {
                if (selectedOrganization) {
                  handleDeleteOrganization(selectedOrganization);
                }
              }}
              sx={{ color: 'error.main' }}
            >
              <ListItemIcon>
                <DeleteIcon color="error" />
              </ListItemIcon>
              <ListItemText primary="删除组织" />
            </MenuOption>
          )}
        </MenuList>
      </Menu>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <WarningIcon color="warning" />
            确认删除
          </Box>
        </DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除组织 "{organizationToDelete?.name}" 吗？
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            此操作不可撤销，请确保该组织下没有用户和数据。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
          <Button
            color="error"
            onClick={confirmDelete}
            disabled={deleteMutation.isLoading}
          >
            {deleteMutation.isLoading ? '删除中...' : '删除'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default OrganizationListPage;